package it.gtd.swimpool.controller.resources;

import it.gtd.swimpool.model.business.FeedbackManager;
import it.gtd.swimpool.model.entity.Feedback;
import it.gtd.swimpool.model.entity.Rating;
import it.gtd.swimpool.model.entity.Skill;
import it.gtd.swimpool.model.entity.User;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Stateless
@Path("/")
public class FeedbackResource extends SecuredResource {
    private static class Comment {
        private String text;
        private int rating;

        public Comment(String text, int rating) {
            this.text = text;
            this.rating = rating;
        }

        public Comment() { }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public int getRating() {
            return rating;
        }

        public void setRating(int rating) {
            this.rating = rating;
        }
    }

    @PersistenceContext
    private EntityManager entityManager;

    @EJB
    private FeedbackManager feedbackManager;

    @GET
    @Path("/self/skills/{sid}/feedbacks")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Feedback> getOwnFeedbacks(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @PathParam("sid") int skillId
    ) {
        User caller = checkUser(sessionId);
        Skill skill = null;

        skill = entityManager.find(Skill.class, skillId);

        return feedbackManager.getFeedbacks(caller, skill);
    }

    @GET
    @Path("/users/{id}/skills/{sid}/feedbacks")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Feedback> getUserFeedbacks(
        @PathParam("id") int id,
        @PathParam("sid") int skillId
    ) {
        User user = entityManager.find(User.class, id);
        Skill skill = null;

        skill = entityManager.find(Skill.class, skillId);

        return feedbackManager.getFeedbacks(user, skill);
    }

    @POST
    @Path("/users/{id}/skills/{sid}/feedbacks")
    @Consumes(MediaType.APPLICATION_JSON)
    public void postFeedback(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @PathParam("id") int id,
        @PathParam("sid") int skillId,
        Comment comment
    ) {
        User caller = checkUser(sessionId);
        User target = entityManager.find(User.class, id);
        Skill skill = skill = entityManager.find(Skill.class, skillId);

        if (comment.getRating() < 1) {
            comment.setRating(1);
        } else if (comment.getRating() > 5) {
            comment.setRating(5);
        }

        Rating r = Rating.values()[comment.getRating() - 1];

        comment.text = escape(comment.text);

        feedbackManager.sendFeedback(caller, target, skill, r, comment.text);
    }
}
